package com.vma.tools.qiniu;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;

public class CdnAntiLeech {
    /**
     * 生成资源基于CDN时间戳防盗链的访问外链
     *
     * @throws MalformedURLException
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */

    public static String getAntiLeechAccessUrlBasedOnTimestamp(String url, String encryptKey, int durationInSeconds)
            throws MalformedURLException, UnsupportedEncodingException, NoSuchAlgorithmException {
        URL urlObj = new URL(url);
        String path = urlObj.getPath();

        long timestampNow = System.currentTimeMillis() / 1000 + durationInSeconds;
        String expireHex = Long.toHexString(timestampNow);

        String toSignStr = String.format("%s%s%s", encryptKey, path, expireHex);
        String signedStr = md5ToLower(toSignStr);

        String signedUrl = null;
        if (urlObj.getQuery() != null) {
            signedUrl = String.format("%s&sign=%s&t=%s", url, signedStr, expireHex);
        } else {
            signedUrl = String.format("%s?sign=%s&t=%s", url, signedStr, expireHex);
        }

        return signedUrl;
    }

    private static String md5ToLower(String src) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(src.getBytes("utf-8"));
        byte[] md5Bytes = digest.digest();
        return Hex.encodeHexString(md5Bytes);
    }

    public static void main(String[] args) throws UnsupportedEncodingException, MalformedURLException, NoSuchAlgorithmException {
        String encryptKey = "ecb8ab98fab8408b378b1b889ab9d39a6ea8888a";

        // 待加密链接
        String fileKey = "IMG_4436.JPG";
        String encodedFileKey = "";

        // 考虑到文件名称会有中文，所以需要做urlencode
        encodedFileKey = URLEncoder.encode(fileKey, "utf-8");
        String urlToSign = String.format("http://www.v-ma.com/%s", encodedFileKey);

        int duration = 3600*12;
        String signedUrl = CdnAntiLeech.getAntiLeechAccessUrlBasedOnTimestamp(urlToSign, encryptKey, duration);
        System.out.println(signedUrl);
    }
}
